package com.ruoyi.system.basicInformation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.basicInformation.vo.TServiceDeploymentTwoVo;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.ruoyi.system.basicInformation.bo.TServiceDeploymentAddBo;
import com.ruoyi.system.basicInformation.bo.TServiceDeploymentQueryBo;
import com.ruoyi.system.basicInformation.bo.TServiceDeploymentEditBo;
import com.ruoyi.system.basicInformation.domain.TServiceDeployment;
import com.ruoyi.system.basicInformation.mapper.TServiceDeploymentMapper;
import com.ruoyi.system.basicInformation.vo.TServiceDeploymentVo;
import com.ruoyi.system.basicInformation.service.ITServiceDeploymentService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 勤务部署基本信息Service业务层处理
 *
 * @author ruoyi
 * @date 2021-05-20
 */
@Service
public class TServiceDeploymentServiceImpl extends ServiceImpl<TServiceDeploymentMapper, TServiceDeployment> implements ITServiceDeploymentService {

    @Autowired
    private ISysDictDataService iSysDictDataService;

    @Override
    public TServiceDeploymentVo queryById(Long id) {
        TServiceDeployment db = this.baseMapper.selectById(id);
        return BeanUtil.toBean(db, TServiceDeploymentVo.class);
    }

    /**
     * 导入用户数据
     *
     * @param userList        APP用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<TServiceDeployment> userList, Boolean isUpdateSupport, String operName) {
        if (Validator.isNull(userList) || userList.size() == 0) {
            throw new CustomException("导入勤务部署信息不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        //String password = configService.selectConfigByKey("sys.user.initPassword");
        for (TServiceDeployment user : userList) {
            if (user.getName().isEmpty() || user.getDeploymentType().isEmpty() || user.getFirstContact().isEmpty()) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、勤务名称 " + user.getName() + " 导入失败,数据不能为空";
                failureMsg.append(msg);
            } else {
                try {
                    String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9])|(16[6]))\\d{8}$";
                    Pattern p = Pattern.compile(regex);
                    Matcher m = p.matcher(user.getFirstContact());  //registrant_phone  ====  电话号码字段
                    Matcher m1 = p.matcher(user.getSpecificContact());  //registrant_phone  ====  电话号码字段
                    if (!m.matches()) {
                        failureNum++;
                        String msg = "<br/>" + failureNum + "、勤务名称 " + user.getName() + " ,导入失败，数据格式错误";
                        failureMsg.append(msg);
                    } else if (!m1.matches()) {
                        failureNum++;
                        String msg = "<br/>" + failureNum + "、勤务名称 " + user.getName() + " ,导入失败，数据格式错误";
                        failureMsg.append(msg);
                    } else {
                        user.setType(iSysDictDataService.selectDictValue("service_deployment_type", user.getDeploymentType()));
                        // 验证是否存在这个用户
                        TServiceDeployment u = baseMapper.selectUserByName(user.getName());
                        if (Validator.isNull(u)) {
                            user.setCreateBy(operName);
                            this.insertShip(user);
                            successNum++;
                            successMsg.append("<br/>" + successNum + "、勤务名称 " + user.getName() + " 导入成功");
                        } else if (isUpdateSupport) {
                            user.setUpdateBy(operName);
                            user.setId(u.getId());
                            this.updateShip(user);
                            successNum++;
                            successMsg.append("<br/>" + successNum + "、勤务名称 " + user.getName() + " 更新成功");
                        } else {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、勤务名称 " + user.getName() + " 已存在");
                        }
                    }
                } catch (Exception e) {
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、勤务名称 " + user.getName() + " 导入失败：";
                    failureMsg.append(msg + e.getMessage());
                    log.error(msg, e);
                }
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertShip(TServiceDeployment user) {

        // 新增用户信息
        int rows = baseMapper.insert(user);

        return rows;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateShip(TServiceDeployment user) {
        Long userId = user.getId();

        return baseMapper.updateById(user);
    }

    @Override
    public List<TServiceDeploymentVo> queryList(TServiceDeploymentQueryBo bo) {
//        LambdaQueryWrapper<TServiceDeployment> lqw = Wrappers.lambdaQuery();
//        lqw.like(StrUtil.isNotBlank(bo.getName()), TServiceDeployment::getName, bo.getName());
//        lqw.eq(StrUtil.isNotBlank(bo.getType()), TServiceDeployment::getType, bo.getType());
//        return entity2Vo(this.list(lqw));
        return this.baseMapper.selectListForExt(bo);
    }

    @Override
    public List<TServiceDeploymentTwoVo> queryListTwo(TServiceDeploymentQueryBo bo) {
//        LambdaQueryWrapper<TServiceDeployment> lqw = Wrappers.lambdaQuery();
//        lqw.like(StrUtil.isNotBlank(bo.getName()), TServiceDeployment::getName, bo.getName());
//        lqw.eq(StrUtil.isNotBlank(bo.getType()), TServiceDeployment::getType, bo.getType());
//        return entity2Vo(this.list(lqw));
        return this.baseMapper.selectListForExtTwo(bo);
    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<TServiceDeploymentVo> entity2Vo(Collection<TServiceDeployment> collection) {
        List<TServiceDeploymentVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, TServiceDeploymentVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<TServiceDeployment> page = (Page<TServiceDeployment>) collection;
            Page<TServiceDeploymentVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(TServiceDeploymentAddBo bo) {
        TServiceDeployment add = BeanUtil.toBean(bo, TServiceDeployment.class);
        validEntityBeforeSave(add);
        return this.save(add);
    }

    @Override
    public Boolean updateByEditBo(TServiceDeploymentEditBo bo) {
        TServiceDeployment update = BeanUtil.toBean(bo, TServiceDeployment.class);
        validEntityBeforeSave(update);
        return this.updateById(update);
    }

    @Override
    public Boolean updateByEditBoExt(TServiceDeploymentEditBo bo) {
        return this.baseMapper.updateByEditBoExt(bo) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(TServiceDeployment entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }

    @Override
    public String checkNameUnique(String name, int id) {
        LambdaQueryWrapper<TServiceDeployment> lqw = Wrappers.lambdaQuery();
        if (id != 0)
            lqw.notIn(TServiceDeployment::getId, id);
        lqw.eq(TServiceDeployment::getName, name);
        lqw.eq(TServiceDeployment::getDelFlag, "0");
        lqw.last("limit 1");
        int count = count(lqw);
        if (count > 0) {
            return "1";
        }
        return "0";
    }
}
